import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/providers/auth_provider.dart';
import '../../../core/providers/curriculum_provider.dart';
import '../../../core/providers/user_extra_info_provider.dart';
import '../../../core/api/api_client.dart';
import '../../../core/api/curriculum/curriculum_model.dart';
import '../../../shared/widgets/aurora_background.dart';
import '../../../shared/widgets/glass_card.dart';
import '../../../shared/utils/responsive_utils.dart';

class CurriculumPage extends ConsumerStatefulWidget {
  const CurriculumPage({super.key});

  @override
  ConsumerState<CurriculumPage> createState() => _CurriculumPageState();
}

class _CurriculumPageState extends ConsumerState<CurriculumPage> {
  @override
  void initState() {
    super.initState();
    // 页面初始化时加载教材大纲
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadCurriculumData();
    });
  }

  Future<void> _loadCurriculumData() async {
    try {
      // 检查用户登录状态和token
      final authState = ref.read(authProvider);
      if (!authState.isLoggedIn || authState.accessToken == null) {
        print('❌ 用户未登录或token未设置，无法获取教材大纲');
        throw Exception('请先登录后再查看教材大纲');
      }

      // 确保token已设置到ApiClient
      ApiClient().setAuthToken(authState.accessToken!);
      print('🔐 已设置认证Token: ${authState.accessToken!.substring(0, 20)}...');

      final userExtraInfo = ref.read(userExtraInfoProvider);

      if (userExtraInfo != null && userExtraInfo.subjectsList.isNotEmpty) {
        // 使用用户的第一个科目和年级信息
        final subject = userExtraInfo.subjectsList.first;
        final grade = userExtraInfo.fullGradeInfo;

        print('📚 获取教材大纲: subject=$subject, grade=$grade');

        await ref
            .read(curriculumProvider.notifier)
            .loadCurriculumBySubjectAndGrade(subject: subject, grade: grade);
      } else {
        // 如果没有用户信息，加载所有教材大纲
        print('📚 获取所有教材大纲');
        await ref.read(curriculumProvider.notifier).loadAllCurriculum();
      }
    } catch (e) {
      print('❌ 获取教材大纲失败: $e');
      rethrow;
    }
  }

  @override
  Widget build(BuildContext context) {
    final curriculumState = ref.watch(curriculumProvider);
    final userExtraInfo = ref.watch(userExtraInfoProvider);

    return Scaffold(
      appBar: AppBar(
        title: const Text('教材大纲'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            if (context.canPop()) {
              context.pop();
            } else {
              context.go('/dashboard');
            }
          },
          tooltip: '返回',
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () => ref.read(curriculumProvider.notifier).refresh(),
          ),
        ],
      ),
      body: Stack(
        children: [
          const AuroraBackground(),
          _buildBody(curriculumState, userExtraInfo),
        ],
      ),
    );
  }

  Widget _buildBody(CurriculumState curriculumState, userExtraInfo) {
    final ColorScheme cs = Theme.of(context).colorScheme;

    if (curriculumState.isLoading) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            Text('正在加载教材大纲...'),
          ],
        ),
      );
    }

    if (curriculumState.error != null) {
      // 检查是否是未登录错误
      final isUnauthorizedError =
          curriculumState.error!.contains('请先登录') ||
          curriculumState.error!.contains('认证失败') ||
          curriculumState.error!.contains('401');

      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              isUnauthorizedError ? Icons.login : Icons.error_outline,
              size: ResponsiveUtils.getResponsiveIconSize(context, 64),
              color: isUnauthorizedError ? cs.primary : cs.error,
            ),
            SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 16)),
            Text(
              isUnauthorizedError ? '需要登录' : '加载失败',
              style: Theme.of(context).textTheme.titleLarge,
            ),
            SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 8)),
            Text(
              isUnauthorizedError ? '请先登录后再查看教材大纲' : curriculumState.error!,
              style: Theme.of(context).textTheme.bodyMedium,
              textAlign: TextAlign.center,
            ),
            SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 16)),
            if (isUnauthorizedError) ...[
              ElevatedButton(
                onPressed: () => context.go('/login'),
                child: const Text('去登录'),
              ),
            ] else ...[
              ElevatedButton(
                onPressed: _loadCurriculumData,
                child: const Text('重试'),
              ),
            ],
          ],
        ),
      );
    }

    if (curriculumState.curriculumList.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.book_outlined,
              size: ResponsiveUtils.getResponsiveIconSize(context, 64),
              color: cs.onSurface.withOpacity(0.5),
            ),
            SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 16)),
            Text('暂无教材大纲', style: Theme.of(context).textTheme.titleLarge),
            SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 8)),
            Text(
              '请先设置您的年级和科目信息',
              style: Theme.of(context).textTheme.bodyMedium,
            ),
            SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 16)),
            ElevatedButton(
              onPressed: () => context.go('/profile-setup'),
              child: const Text('去设置'),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: () => ref.read(curriculumProvider.notifier).refresh(),
      child: ListView(
        padding: EdgeInsets.all(
          ResponsiveUtils.getResponsiveSpacing(context, 16),
        ),
        children: [
          // 用户信息卡片
          if (userExtraInfo != null) ...[
            GlassCard(
              child: Padding(
                padding: EdgeInsets.all(
                  ResponsiveUtils.getResponsiveSpacing(context, 16),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '当前学习',
                      style: Theme.of(context).textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      '年级：${userExtraInfo.fullGradeInfo}',
                      style: Theme.of(context).textTheme.bodyMedium,
                    ),
                    GestureDetector(
                      onTap:
                          () =>
                              _showSubjectSelector(context, ref, userExtraInfo),
                      child: Row(
                        children: [
                          Text(
                            '科目：${userExtraInfo.subjectsList.join('、')}',
                            style: Theme.of(
                              context,
                            ).textTheme.bodyMedium?.copyWith(
                              color: cs.primary,
                              decoration: TextDecoration.underline,
                            ),
                          ),
                          const SizedBox(width: 4),
                          Icon(Icons.edit, size: 16, color: cs.primary),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),
          ],

          // 教材大纲列表
          ...curriculumState.curriculumList
              .map((curriculum) => _CurriculumCard(curriculum: curriculum))
              .toList(),
        ],
      ),
    );
  }

  // 显示科目选择器
  void _showSubjectSelector(
    BuildContext context,
    WidgetRef ref,
    UserExtraInfo userExtraInfo,
  ) {
    final List<String> availableSubjects = [
      '数学',
      '语文',
      '英语',
      '物理',
      '化学',
      '生物',
      '历史',
      '地理',
      '政治',
    ];
    final List<String> currentSubjects = userExtraInfo.subjectsList;

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('选择科目'),
          content: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              return Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Text('请选择您要学习的科目：'),
                  const SizedBox(height: 16),
                  Wrap(
                    spacing: 8,
                    runSpacing: 8,
                    children:
                        availableSubjects.map((subject) {
                          final isSelected = currentSubjects.contains(subject);
                          return FilterChip(
                            label: Text(subject),
                            selected: isSelected,
                            onSelected: (selected) {
                              setState(() {
                                if (selected) {
                                  if (!currentSubjects.contains(subject)) {
                                    currentSubjects.add(subject);
                                  }
                                } else {
                                  currentSubjects.remove(subject);
                                }
                              });
                            },
                          );
                        }).toList(),
                  ),
                ],
              );
            },
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () async {
                if (currentSubjects.isNotEmpty) {
                  await _updateUserSubjects(ref, currentSubjects);
                  Navigator.of(context).pop();
                } else {
                  ScaffoldMessenger.of(
                    context,
                  ).showSnackBar(const SnackBar(content: Text('请至少选择一个科目')));
                }
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  // 更新用户科目信息
  Future<void> _updateUserSubjects(
    WidgetRef ref,
    List<String> newSubjects,
  ) async {
    try {
      final userExtraInfoNotifier = ref.read(userExtraInfoProvider.notifier);
      final currentUserInfo = ref.read(userExtraInfoProvider);

      if (currentUserInfo != null) {
        // 更新本地状态
        await userExtraInfoNotifier.updateUserExtraInfo(
          UserExtraInfo(
            grade: currentUserInfo.grade,
            volume: currentUserInfo.volume,
            subjects: newSubjects.join('/'),
            goals: currentUserInfo.goals,
          ),
        );

        // 重新加载教材大纲
        await _loadCurriculumData();

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('科目已更新为：${newSubjects.join('、')}')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('更新科目失败：$e')));
    }
  }
}

// 教材大纲卡片
class _CurriculumCard extends StatelessWidget {
  final CurriculumOutline curriculum;

  const _CurriculumCard({required this.curriculum});

  @override
  Widget build(BuildContext context) {
    final ColorScheme cs = Theme.of(context).colorScheme;

    return GlassCard(
      child: Padding(
        padding: EdgeInsets.all(
          ResponsiveUtils.getResponsiveSpacing(context, 16),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  Icons.book,
                  color: cs.primary,
                  size: ResponsiveUtils.getResponsiveIconSize(context, 24),
                ),
                SizedBox(
                  width: ResponsiveUtils.getResponsiveSpacing(context, 12),
                ),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        curriculum.title,
                        style: Theme.of(context).textTheme.titleMedium
                            ?.copyWith(fontWeight: FontWeight.bold),
                      ),
                      SizedBox(
                        height: ResponsiveUtils.getResponsiveSpacing(
                          context,
                          4,
                        ),
                      ),
                      Text(
                        '${curriculum.subject} · ${curriculum.grade}${curriculum.volume}',
                        style: Theme.of(context).textTheme.bodySmall?.copyWith(
                          color: cs.onSurface.withOpacity(0.6),
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: ResponsiveUtils.getResponsiveSpacing(
                      context,
                      8,
                    ),
                    vertical: ResponsiveUtils.getResponsiveSpacing(context, 4),
                  ),
                  decoration: BoxDecoration(
                    color: cs.primaryContainer,
                    borderRadius: BorderRadius.circular(
                      ResponsiveUtils.getResponsiveRadius(context, 12),
                    ),
                  ),
                  child: Text(
                    '${curriculum.chapters.length} 章',
                    style: TextStyle(
                      fontSize: ResponsiveUtils.getResponsiveFontSize(
                        context,
                        12,
                      ),
                      color: cs.onPrimaryContainer,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ],
            ),

            if (curriculum.description != null) ...[
              SizedBox(
                height: ResponsiveUtils.getResponsiveSpacing(context, 12),
              ),
              Text(
                curriculum.description!,
                style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                  color: cs.onSurface.withOpacity(0.8),
                ),
              ),
            ],

            SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 16)),

            // 树形章节列表
            Text(
              '章节结构',
              style: Theme.of(
                context,
              ).textTheme.titleSmall?.copyWith(fontWeight: FontWeight.w600),
            ),
            SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 8)),

            // 树形展示章节
            _TreeView(chapters: curriculum.chapters),

            SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 16)),
          ],
        ),
      ),
    );
  }
}

// 树形视图组件
class _TreeView extends StatefulWidget {
  final List<Chapter> chapters;

  const _TreeView({required this.chapters});

  @override
  State<_TreeView> createState() => _TreeViewState();
}

class _TreeViewState extends State<_TreeView> {
  final Set<String> _expandedNodes = <String>{};

  @override
  Widget build(BuildContext context) {
    return Column(
      children:
          widget.chapters
              .map(
                (chapter) => _TreeNode(
                  chapter: chapter,
                  expandedNodes: _expandedNodes,
                  onToggle: (nodeId) {
                    setState(() {
                      if (_expandedNodes.contains(nodeId)) {
                        _expandedNodes.remove(nodeId);
                      } else {
                        _expandedNodes.add(nodeId);
                      }
                    });
                  },
                ),
              )
              .toList(),
    );
  }
}

// 树节点组件
class _TreeNode extends StatelessWidget {
  final Chapter chapter;
  final int level;
  final Set<String> expandedNodes;
  final Function(String) onToggle;

  const _TreeNode({
    required this.chapter,
    this.level = 0,
    required this.expandedNodes,
    required this.onToggle,
  });

  @override
  Widget build(BuildContext context) {
    final ColorScheme cs = Theme.of(context).colorScheme;
    final indent = level * 20.0;
    final isExpanded = expandedNodes.contains(chapter.id);
    final hasChildren = chapter.knowledgePoints.isNotEmpty;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          margin: EdgeInsets.only(left: indent),
          child: InkWell(
            onTap: hasChildren ? () => onToggle(chapter.id) : null,
            borderRadius: BorderRadius.circular(
              ResponsiveUtils.getResponsiveRadius(context, 8),
            ),
            child: Padding(
              padding: EdgeInsets.symmetric(
                vertical: ResponsiveUtils.getResponsiveSpacing(context, 8),
                horizontal: ResponsiveUtils.getResponsiveSpacing(context, 4),
              ),
              child: Row(
                children: [
                  // 展开/收起图标
                  if (hasChildren) ...[
                    Icon(
                      isExpanded ? Icons.expand_more : Icons.chevron_right,
                      size: ResponsiveUtils.getResponsiveIconSize(context, 20),
                      color: cs.primary,
                    ),
                    SizedBox(
                      width: ResponsiveUtils.getResponsiveSpacing(context, 4),
                    ),
                  ] else ...[
                    SizedBox(
                      width: ResponsiveUtils.getResponsiveSpacing(context, 24),
                    ), // 占位，保持对齐
                  ],

                  // 层级指示器
                  if (level > 0) ...[
                    Icon(
                      Icons.subdirectory_arrow_right,
                      size: ResponsiveUtils.getResponsiveIconSize(context, 16),
                      color: cs.primary.withOpacity(0.6),
                    ),
                    SizedBox(
                      width: ResponsiveUtils.getResponsiveSpacing(context, 4),
                    ),
                  ],

                  // 章节图标 - 根据层级显示不同图标
                  Icon(
                    _getIconForLevel(level),
                    size: ResponsiveUtils.getResponsiveIconSize(context, 18),
                    color: _getColorForLevel(level, cs),
                  ),
                  SizedBox(
                    width: ResponsiveUtils.getResponsiveSpacing(context, 8),
                  ),

                  // 章节标题和描述
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          chapter.title,
                          style: _getTextStyleForLevel(level, context).copyWith(
                            fontWeight: _getFontWeightForLevel(level),
                            color: _getColorForLevel(level, cs),
                          ),
                        ),
                        if (chapter.description != null &&
                            chapter.description!.isNotEmpty) ...[
                          SizedBox(
                            height: ResponsiveUtils.getResponsiveSpacing(
                              context,
                              2,
                            ),
                          ),
                          Text(
                            chapter.description!,
                            style: Theme.of(
                              context,
                            ).textTheme.bodySmall?.copyWith(
                              color: cs.onSurface.withOpacity(0.6),
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ],
                      ],
                    ),
                  ),

                  // 知识点数量
                  if (hasChildren)
                    Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: ResponsiveUtils.getResponsiveSpacing(
                          context,
                          6,
                        ),
                        vertical: ResponsiveUtils.getResponsiveSpacing(
                          context,
                          2,
                        ),
                      ),
                      decoration: BoxDecoration(
                        color: cs.secondaryContainer,
                        borderRadius: BorderRadius.circular(
                          ResponsiveUtils.getResponsiveRadius(context, 8),
                        ),
                      ),
                      child: Text(
                        '${chapter.knowledgePoints.length}',
                        style: TextStyle(
                          fontSize: ResponsiveUtils.getResponsiveFontSize(
                            context,
                            10,
                          ),
                          color: cs.onSecondaryContainer,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                ],
              ),
            ),
          ),
        ),

        // 子章节递归显示
        if (hasChildren && isExpanded) ...[
          const SizedBox(height: 4),
          ...chapter.knowledgePoints.map(
            (knowledgePoint) => _TreeNode(
              chapter: Chapter(
                id: knowledgePoint.id,
                title: knowledgePoint.title,
                order: knowledgePoint.order,
                knowledgePoints: [], // 暂时为空，后续可以添加更深层的知识点
                description: knowledgePoint.description,
                difficulty: knowledgePoint.difficulty,
              ),
              level: level + 1,
              expandedNodes: expandedNodes,
              onToggle: onToggle,
            ),
          ),
        ],

        const SizedBox(height: 4),
      ],
    );
  }

  // 根据层级获取图标
  IconData _getIconForLevel(int level) {
    switch (level) {
      case 0:
        return Icons.book; // 教材总目录
      case 1:
        return Icons.menu_book; // 主要章节
      case 2:
        return Icons.topic; // 子章节
      case 3:
        return Icons.school; // 具体知识点
      default:
        return Icons.topic;
    }
  }

  // 根据层级获取颜色
  Color _getColorForLevel(int level, ColorScheme cs) {
    switch (level) {
      case 0:
        return cs.primary; // 教材总目录 - 主色调
      case 1:
        return cs.primary; // 主要章节 - 主色调
      case 2:
        return cs.secondary; // 子章节 - 次要色调
      case 3:
        return cs.onSurface; // 具体知识点 - 普通文本色
      default:
        return cs.onSurface;
    }
  }

  // 根据层级获取字体粗细
  FontWeight _getFontWeightForLevel(int level) {
    switch (level) {
      case 0:
      case 1:
        return FontWeight.w600; // 教材总目录和主要章节 - 粗体
      case 2:
        return FontWeight.w500; // 子章节 - 中等粗细
      case 3:
        return FontWeight.normal; // 具体知识点 - 正常粗细
      default:
        return FontWeight.normal;
    }
  }

  // 根据层级获取文本样式
  TextStyle _getTextStyleForLevel(int level, BuildContext context) {
    switch (level) {
      case 0:
        return Theme.of(context).textTheme.titleMedium ??
            const TextStyle(); // 教材总目录
      case 1:
        return Theme.of(context).textTheme.bodyLarge ??
            const TextStyle(); // 主要章节
      case 2:
        return Theme.of(context).textTheme.bodyMedium ??
            const TextStyle(); // 子章节
      case 3:
        return Theme.of(context).textTheme.bodySmall ??
            const TextStyle(); // 具体知识点
      default:
        return Theme.of(context).textTheme.bodyMedium ?? const TextStyle();
    }
  }
}
